// pages/waiter/print/print.js
import Big from 'big.js'
const request = require('@/utils/request.js')
const constants = require('@/utils/khyConstants.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderInfo: {
      goodsType: '',//物品类型
      insureStatus: '',//是否保价
      declarationValue: '',//声明价值
      insureValue: '',//保价金额
      packageState: '0',//快递状态_已下单
      payState: '0',//付款状态_未付款
      startStation: '',
      startStationName: '',
      senderName: '',
      senderPhone: '',
      endStation: '',
      endStationName: '',
      consigneeName: '',
      consigneePhone: '',
      goodsName: '',
      goodsWeight: '',
      goodsLong: '',
      goodsWidth: '',
      goodsHeight: '',
      payMode: '',
      goodsFreight: '',
      goodsPhoto:'',
      outerPackType: '',//包装类型
      outerPackNum: '',//包装数量
      discountValue: 0,//优惠金额
      couponId: '',//优惠卷id
      couponName: '',//优惠卷名称
    },
    requireList: {
      senderPhone: '请录入寄件信息',
      consigneePhone: '请录入收件信息',
      goodsName: '请录入物品信息',
      // goodsWeight: '请录入物品重量',
      // goodsLong: '请录入物品长',
      // goodsWidth: '请录入物品宽',
      // goodsHeight: '请录入物品高',
      //goodsPhoto: '物品照片',
      goodsFreight: '请录入付款金额',
      payMode: '请选择付款方式',
    },
    payModeName: '',
    goodsTypeName: '',
    outerPackTypeName: '',
    insureStatusName: '',
    goodsTypeVisible: false,
    outerPackTypeVisible: false,
    insureStatusVisible: false,
    payModeVisible: false,
    insureStatusList: getApp().globalData.dictData['insureStatus'],
    goodsTypeList: getApp().globalData.dictData['goodsType'],
    payModeList: getApp().globalData.dictData['payMode'],
    outerPackTypeList: getApp().globalData.dictData['outerPackType'],
    payStateVisible: false,
    payStateName: '',
    payStateList: getApp().globalData.dictData['payState'],
    basePrice: getApp().globalData.basePrice, //预估底价
    insureRate: getApp().globalData.insureRate,//保价费用比例
    diffValue: getApp().globalData.diffValue,//体积转换重量的差值
    incrementPrice: getApp().globalData.incrementPrice,//每公斤续重价格
    imgList:[],// 上传的图片
    couponData: null,//优惠卷数据
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {debugger
    const app = getApp();
    this.setData({
        order_bg:app.globalData.nginxIp+'/img/order_bg.png',
        order_bg_text:app.globalData.nginxIp+'/img/order_bg_text.png',
    })
    //清理优惠卷
    getApp().globalData.pageData[constants.page_couponSelect] = {}

    let orderData = getApp().globalData.pageData[constants.page_waiterprint]
    if (orderData) {

      let obj = {}
      for (const key in orderData) {
        if (orderData.hasOwnProperty(key)) {
          obj['orderInfo.' + key] = orderData[key]
        }
      }
      //付款类型下拉初始化
      if (orderData.payMode == '1') {
        obj['payModeName'] = this.data.payModeList[0]['label']
      } else {
        obj['payModeName'] = this.data.payModeList[1]['label']
      }
      //是否保价初始化
      if (orderData.insureStatus == '1') {
        obj['insureStatusName'] = this.data.insureStatusList[1]['label']
      } else {
        obj['insureStatusName'] = this.data.insureStatusList[0]['label']
      }
      //物品类型下拉初始化
      if (orderData.goodsType) {
        this.data.goodsTypeList.forEach(item => {
          if (orderData.goodsType == item['value']) {
            obj['goodsTypeName'] = item['label']
          }
        })
      }
      // if (orderData.payState == '1') {
      //   obj['payStateName'] = this.data.payStateList[1]['label']
      // } else {
      //   obj['payStateName'] = this.data.payStateList[0]['label']
      // }
      let goodsPhoto=orderData.goodsPhoto.split(",")
      let imgList=[];
      if(goodsPhoto.length>0){
        goodsPhoto.forEach((item)=>{
            if(item!= ""){
                imgList.push(app.globalData.nginxIp+"/"+item)
            }
        })
        obj['imgList']=imgList
      }
      this.setData(obj)

      //获取优惠卷信息,并计算价格
      this.getCouponData(orderData)
    }

    this.getParamInfo()
  },

  getCouponData(orderData) {
    if (orderData.couponId) {
      let user = getApp().getUserInfo()
      request.get('/UserController/getUserCouponById', {keyId: orderData.couponId}).then(res => {
        debugger
        if (res.data.code == constants.resultSuccessCode
          && res.data.result) {
            this.setData({
              couponData: res.data.result || {}
            })

            this.calPrice()
        }
      })
    } else {
      this.calPrice()
    }
  },

  getParamInfo() {
    request.get('/HomeController/getDictData', {dictCode: getApp().globalData.paramDictCode + "," + getApp().globalData.outerPackTypeDictCode}).then(res => {
      if (res.data.code == constants.resultSuccessCode
        && res.data.result) {

          let outerPackTypeResult = res.data.result[getApp().globalData.outerPackTypeDictCode] || []
          if (outerPackTypeResult.length > 0) {
            let outerPackTypeList = []
            outerPackTypeResult.forEach(item => {
              let obj = {}
              obj.label = item['itemText'] || ''
              obj.value = item['itemValue'] || ''
              obj.price = item['itemFilter'] || ''
              outerPackTypeList.push(obj)
            })

            this.setData({
              outerPackTypeList: outerPackTypeList
            })
          }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    //处理优惠卷
    let couponData = getApp().globalData.pageData[constants.page_couponSelect]
    if (couponData && couponData.keyId) {
      this.setData({
        couponData: couponData,
        'orderInfo.couponId': couponData['keyId'] || '',
        'orderInfo.couponName': couponData['couponName'] || '',
      })
      this.calPrice()
    }
  },
  //计算价格
  calPrice() {
    let price = new Big(this.data.basePrice)

    if (this.data.orderInfo.goodsType == '4') {//需要计算重量体积
      
      let volume = new Big(0)//体积值
      let calValue = this.data.orderInfo.goodsWeight ? new Big(this.data.orderInfo.goodsWeight) : new Big(0)

      if (this.data.orderInfo.goodsLong && this.data.orderInfo.goodsWidth && this.data.orderInfo.goodsHeight) {
        volume = new Big(this.data.orderInfo.goodsLong).times(new Big(this.data.orderInfo.goodsWidth)).times(new Big(this.data.orderInfo.goodsHeight)).div(new Big(this.data.diffValue)).round(0,Big.roundUp)
      }

      if (volume.cmp(calValue) > 0) {
        calValue = volume
      }
      if (calValue.toNumber() > 0) {
        if (calValue.toNumber() > 1) {
          price = price.plus(calValue.round(0,Big.roundUp).minus(new Big(1)).times(new Big(this.data.incrementPrice)))
        }
      }
    }

    if (this.data.orderInfo.outerPackType && this.data.orderInfo.outerPackType != '6' && this.data.orderInfo.outerPackNum) {
      let packPrice = 0//包装类型单价
      let packType = this.data.orderInfo.outerPackType
      this.data.outerPackTypeList.forEach(item => {
        if (packType == item['value']) {
          packPrice = item['price']
        }
      })

      price = price.plus(new Big(packPrice).times(new Big(this.data.orderInfo.outerPackNum)))
    }
    //保价费用
    if (this.data.orderInfo.insureStatus == '1' && this.data.orderInfo.insureValue) {
      price = price.plus(new Big(this.data.orderInfo.insureValue))
    }
    //计算优惠金额
    let discountValue = new Big(this.data.orderInfo.discountValue || 0)
    if (this.data.couponData && this.data.couponData.keyId) {
      if (this.data.couponData.couponType == constants.couponType_money) {
        //现金卷
        discountValue = new Big(this.data.couponData.couponValue)
      } else {//折扣卷
        let newPrice = new Big(this.data.couponData.couponValue).times(price).div(new Big(10)).round(2,Big.roundUp)
        discountValue = price.minus(newPrice)
      }
      this.setData({
        [`orderInfo.discountValue`]: discountValue.toNumber()
      })
    }

    if (discountValue.cmp(price) > 0) {
      price = new Big(0)
    } else {
      price = price.minus(discountValue)
    }
    this.setData({
      [`orderInfo.goodsFreight`]: price.toNumber()
    })
  },

  onInput(e) {
    let name = e.currentTarget.dataset.name
    let value = e.detail.value
    if (name == 'declarationValue' && new Big(value).toNumber() > getApp().globalData.maxInsureValue) {
      value = getApp().globalData.maxInsureValue
    }
    this.setData({
      [`orderInfo.${name}`]: value
    })

    if (name == 'goodsFreight') {
      return 
    }

    if (name == 'declarationValue') {//声明价值字段逻辑
      let calVaule = value
      if (calVaule) {
        if (calVaule > getApp().globalData.maxInsureValue) {
          calVaule = getApp().globalData.maxInsureValue
        }
        let insureValue = new Big(calVaule).times(new Big(this.data.insureRate))
        if (insureValue.toNumber() < 1) {
          insureValue = 1
        } else {
          insureValue = insureValue.round().toNumber()
        }
        this.setData({
          [`orderInfo.insureValue`]: insureValue
        })
      } else {
        this.setData({
          [`orderInfo.insureValue`]: ''
        })
      }
      
    }

    this.calPrice()
  },

  onPayPicker(e) {
    let name = e.currentTarget.dataset.name
    if (name == 'payModeName') {
      this.setData({
        payModeVisible: true
      })
    } else if (name == 'goodsTypeName') {
      this.setData({
        goodsTypeVisible: true
      })
    }  else if (name == 'outerPackTypeName') {
      this.setData({
        outerPackTypeVisible: true
      })
    } else {
      this.setData({
        insureStatusVisible: true
      })
    } 
    
  },

  onPickerCancel(e) {
    this.setData({
      payModeVisible: false,
      goodsTypeVisible: false,
      outerPackTypeVisible: false,
      insureStatusVisible: false,
    })
  },

  // onStateChange(e) {
  //   const { value } = e.detail;
  //   const { label } = e.detail;

  //   console.log('picker change:', e.detail);
  //   this.setData({
  //     'orderInfo.payState': value[0],
  //     payStateName: label[0],
  //     payStateVisible: false
  //   })
  // },
  onModeChange(e) {
    const { value } = e.detail;
    const { label } = e.detail;

    this.setData({
      'orderInfo.payMode': value[0],
      payModeName: label[0],
      payModeVisible: false
    })
  },

  onGoodsChange(e) {
    const { value } = e.detail;
    const { label } = e.detail;

    this.setData({
      'orderInfo.goodsType': value[0],
      goodsTypeName: label[0],
      goodsTypeVisible: false
    })

    this.calPrice()
  },

  onInsureChange(e) {
    const { value } = e.detail;
    const { label } = e.detail;

    this.setData({
      'orderInfo.insureStatus': value[0],
      insureStatusName: label[0],
      insureStatusVisible: false
    })

    if (value[0] == '0') {
      this.setData({
        'orderInfo.declarationValue': '',
        'orderInfo.insureValue': ''
      })
    }

    this.calPrice()
  },

  onPackTypeChange(e) {
    const { value } = e.detail;
    const { label } = e.detail;

    this.setData({
      'orderInfo.outerPackType': value[0],
      outerPackTypeName: label[0],
      outerPackTypeVisible: false
    })

    this.calPrice()
  },

  maxViewImg(e){
    let imgUrl=e.currentTarget.dataset.img
    wx.previewImage({
        current:imgUrl,
        urls: [imgUrl],
    })
  },

  onCouponClick(e) {
    wx.navigateTo({
      url: '/pages/mypage/couponSelect/couponSelect?userNo=' + this.data.orderInfo.userNo,
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  printClick() {
    for (const key in this.data.requireList) {
      if (!this.data.orderInfo[key]) {
        wx.showToast({
          title: this.data.requireList[key],
          icon: 'error',
          duration: 2000
        })
        return
      }
    }

    let user = getApp().getUserInfo()
    let data = Object.assign({}, this.data.orderInfo, {packageState: '1', tallyClerk: user.userNo || '', tallyClerkName: user.userName || ''})
    request.post('/UserController/savePackage', data).then(res => {

      if (res.data.code == constants.resultSuccessCode) {
        getApp().globalData.pageData[constants.page_print] = res.data.result
        wx.navigateTo({
          url: '/pages/print/print',
        })
      }
    })


    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})